package result

import (
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strconv"
	"test/unit_function/sshdata"
	"time"
)

func mergeResult() {

}

type Benchmark struct {
	Version                 string
	DownloadLink            string
	MuslBenchmarkFilePath   string
	BionicBenchmarkFilePath string
	XtsFilePath             string
}

type TempXml struct {
	XMLName   xml.Name `xml:"testsuites"`
	Failures  string   `xml:"failures,attr"`
	Tests     string   `xml:"tests,attr"`
	Testsuite Testsuite
}

type Testsuite struct {
	XMLName   xml.Name   `xml:"testsuite"`
	TestCases []Testcase `xml:"testcase"`
}

type Testcase struct {
	XMLName xml.Name `xml:"testcase"`
	Name    string   `xml:"name,attr"`
	Message string   `xml:"message,attr"`
	Result  string   `xml:"result,attr"`
}

func GetResult(obj Benchmark) ResultEntity {
	xtsResult := getXtsResult(obj.XtsFilePath)
	benchmarkResult := getBenchmarkResult(obj.MuslBenchmarkFilePath, obj.BionicBenchmarkFilePath)
	entity := ResultEntity{
		Version:      obj.Version,
		DownloadLink: obj.DownloadLink,
		Datetime:     time.Now(),
		Xts:          xtsResult,
		Benchmark:    benchmarkResult,
	}

	return entity
}

func getXtsResult(xtsFilePath string) XtsResult {
	// 直接拿summary_report.xml的数据
	name := xtsFilePath + "/summary_report.xml"
	file, err := os.Open(name)
	if err != nil {
		log.Println("open", name, "failed error msg:", err)
	}
	defer file.Close()
	all, err := io.ReadAll(file)
	if err != nil {
		log.Println("read", name, "failed error msg:", err)
	}
	v := TempXml{}
	err = xml.Unmarshal([]byte(all), &v)
	if err != nil {
		log.Println("xml.Unmarshal", name, "failed error msg:", err)
	}
	total, err := strconv.Atoi(v.Tests)
	if err != nil {
		log.Println("atoi total failed error msg:", err)
	}
	failures, err := strconv.Atoi(v.Failures)
	if err != nil {
		log.Println("atoi failures failed error msg:", err)
	}
	var FailureTestCase []FailureCase
	for _, testCase := range v.Testsuite.TestCases {
		if testCase.Result == "false" {
			failureCase := FailureCase{
				Name:   testCase.Name,
				Reason: testCase.Message,
			}
			FailureTestCase = append(FailureTestCase, failureCase)
		}
	}
	result := XtsResult{
		Total:           total,
		FailureNum:      failures,
		FailureTestCase: FailureTestCase,
	}
	saveXtsFailedTime(failures)
	return result
}

func getBenchmarkResult(MuslBenchmarkFilePath, BionicBenchmarkFilePath string) BenchMarkResult {
	muslFile, err := os.Open(MuslBenchmarkFilePath)
	if err != nil {
		log.Println("open file MuslBenchmarkFilePath failed error msg:", err)
	}
	defer muslFile.Close()
	all, err := io.ReadAll(muslFile)
	if err != nil {
		log.Println("read file MuslBenchmarkFilePath failed error msg:", err)
	}
	bionicFile, err := os.Open(BionicBenchmarkFilePath)
	if err != nil {
		log.Println("open file BionicBenchmarkFilePath failed error msg:", err)
	}
	defer bionicFile.Close()
	all2, err := io.ReadAll(bionicFile)
	if err != nil {
		log.Println("read file BionicBenchmarkFilePath failed error msg:", err)
	}
	return BenchMarkResult{
		MuslBenchmark:   template.HTML(string(all)),
		BionicBenchmark: template.HTML(string(all2)),
	}
}

// 获取HTML的结果
func GetHtmlResult() string {
	download_dailyhtmlfile()
	IndexHtml, err := os.Open("D:/auto_test/result/html/Index.html")
	if err != nil {
		log.Println("open file Index.html failed error msg:", err)
	}
	defer IndexHtml.Close()
	all1, err := io.ReadAll(IndexHtml)
	if err != nil {
		log.Println("read file MuslBenchmarkFilePath failed error msg:", err)
	}
	FailedHtml, err := os.Open("D:/auto_test/result/html/failed files list.html")
	if err != nil {
		log.Println("open file BionicBenchmarkFilePath failed error msg:", err)
	}
	defer FailedHtml.Close()
	all2, err := io.ReadAll(FailedHtml)
	if err != nil {
		log.Println("read file BionicBenchmarkFilePath failed error msg:", err)
	}
	TotalHmtl, err := os.Open("D:/auto_test/result/html/total file list.html")
	if err != nil {
		log.Println("open file BionicBenchmarkFilePath failed error msg:", err)
	}
	defer TotalHmtl.Close()
	all3, err := io.ReadAll(TotalHmtl)
	if err != nil {
		log.Println("read file BionicBenchmarkFilePath failed error msg:", err)
	}
	return string(all1) + string(all2) + string(all3)
}
func download_dailyhtmlfile() {
	fmt.Println("download_dailyhtmlfile")
	//上传
	client := sshdata.GetConnection()
	defer client.Close()
	result := sshdata.UploadFile("/mnt/data/ywx1293154/script_getdailytest.sh", "script/script_getdailytest.sh", client, "0744")
	if !result {
		log.Println("upload file script_getdailytest failed")
	}
	log.Println("uploadFile  script_getdailytest succeed")
	//执行
	session, err := client.NewSession()
	if err != nil {
		log.Println("Rk3568Xts newSession failed, error=", err)
		os.Exit(1)
	}
	defer session.Close()
	log.Println("executing script_getdailytest.sh")
	err = session.Run("~/script_getdailytest.sh > ~/script_getdailytest.log")
	if err != nil {
		log.Println("Rk3568Xts run script failed, error=", err)
		os.Exit(1)
	}
	log.Println("executing script_getdailytest.sh succeed!")
	//下载
	now := time.Now()
	dateStr := string(now.Format("2006-01-02"))
	sshdata.DownloadFile("/mnt/data/ywx1293154/daily_test/daily_test/report/checksec/"+dateStr+"/Index.html",
		"D:/auto_test/result/html/Index.html", client)
	sshdata.DownloadFile("/mnt/data/ywx1293154/daily_test/daily_test/report/checksec/"+dateStr+"/total file list.html",
		"D:/auto_test/result/html/total file list.html", client)
	sshdata.DownloadFile("/mnt/data/ywx1293154/daily_test/daily_test/report/checksec/"+dateStr+"/failed files list.html",
		"D:/auto_test/result/html/failed files list.html", client)
}
func saveXtsFailedTime(times int) {
	now := time.Now()
	dateStr := now.Format("2006-01-02")
	fileName := "D:/auto_test/xts/failed_times/" + string(dateStr) + ".txt"
	fmt.Printf("cur fileName:%s times:%d \n", fileName, times)
	file, err := os.Create(fileName)
	if err != nil {
		log.Fatalf("创建文件失败: %v", err)
	}
	defer file.Close()

	str := strconv.Itoa(times)
	data := []byte(str)
	if _, err := file.Write(data); err != nil {
		log.Fatalf("写入文件失败: %v", err)
	}
}

// 获取折线图的结果
func GetLineChart() string {
	now := time.Now()
	result := LineChart{
		Date:  make([]string, 7),
		Times: make([]string, 7),
	}
	for i := 0; i < 7; i++ {
		sevenDaysAgo := now.AddDate(0, 0, i-6)
		dateStr := sevenDaysAgo.Format("2006-01-02")
		result.Date[i] = dateStr

		FilePath := "D:/auto_test/xts/failed_times/" + dateStr + ".txt"
		TimesFile, err := os.Open(FilePath)
		if err != nil {
			result.Times[i] = "0"
			log.Println("open file TimesFile failed error msg and Date", err, dateStr)
		} else {
			defer TimesFile.Close()
			all1, err := io.ReadAll(TimesFile)
			if err != nil {
				result.Times[i] = "0"
				log.Println("read file TimesFile failed error msg and Date", err, dateStr)
			} else {
				result.Times[i] = string(all1)
			}
		}
		fmt.Printf("日期:%s xts测试失败 次数:%s\n", dateStr, result.Times[i])
	}
	jsonData, err := json.Marshal(result)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		os.Exit(1)
	}
	jsonArg := fmt.Sprintf(`'%s'`, string(jsonData))
	fmt.Printf("七天前的日期:%s\n", jsonArg)
	cmd := exec.Command("python", "D:/auto_test/test_script_for_openharmony/pyscript/generate_linechart.py", jsonArg)
	cmd.Dir = "D:/auto_test/result/html"
	err = cmd.Run()
	if err != nil {
		fmt.Println("Error executing Python script:", err)
		os.Exit(1)
	}
	return EmbeddedHtml("D:/auto_test/result/html/linechart.png")
}

func EmbeddedHtml(PictureFilePath string) string {
	imgData, err := ioutil.ReadFile(PictureFilePath)
	if err != nil {
		log.Fatal(err)
	}
	imgBase64 := base64.StdEncoding.EncodeToString(imgData)
	htmlContent := `
	<!DOCTYPE html>
	<html lang="en">
	<head>
	<meta charset="UTF-8">
	<title>Embedded Image Example</title>
	</head>
	<body>
	<img src="data:image/png;base64,` + imgBase64 + `" alt="Embedded Image">
	</body>
	</html>
	`
	return htmlContent
}
